package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hmall.item.config.MqConfig;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.PageDTO;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/stock/{itemId}/{num}")
    public void deleteOrder(@PathVariable("itemId") Long itemId,
                            @PathVariable("num") Integer num
    ){
        Item item = itemService.getById(itemId);
        item.setStock(item.getStock()-num);
        itemService.updateById(item);


    }

    /**
     * 分页查询商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> PageResult(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "1") Integer size){
        Page<Item> itemPage = itemService.page(new Page<>(page, size));
        return new PageDTO(itemPage.getTotal(),itemPage.getRecords());
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item QueryById(@PathVariable("id") Long id ){
        return itemService.getById(id);

    }

    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void addItem(@RequestBody Item item){
        itemService.save(item);

    }

    /**
     * 商品上架，下架
     */
    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable("id") Long id,
                       @PathVariable("status") Integer status){
        Item item = itemService.getById(id);

        item.setStatus(status);
        itemService.updateById(item);
        if(status==1){
            rabbitTemplate.convertAndSend(MqConstants.Item_EXCHANGE,MqConstants.Item_INSERT_KEY,item.getId());
        }else if (status==2){

        }
        rabbitTemplate.convertAndSend(MqConstants.Item_EXCHANGE,MqConstants.Item_DELETE_KEY,item.getId());

    }


    /**
     * 修改商品
     */
    @PutMapping
    public void updateItem(@RequestBody Item item){
        itemService.updateById(item);

    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public void  deleteItem(@PathVariable("id") Long id){
        itemService.removeById(id);

    }




}
